package com.game.thrones.domain.IdEntity;

import java.util.Date;

import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

import com.game.thrones.constant.Errors;
import com.game.thrones.domain.KbmContent;
import com.game.thrones.exception.GameGlobalException;

/**
 * 继承IdEntityAuto的对象，在创建或更新前自动加入时间戳
 * 
 * @author sunyang
 *
 */
public class IdEntityAutoListener {

	@PrePersist
	public void prePersist(IdEntityAuto idEntityAuto) {
		Date now = new Date();
		idEntityAuto.setCreateTime(now);
		idEntityAuto.setModifyTime(now);
		KbmContent kbmContent = idEntityAuto.getKbmContent();
		if (kbmContent == null) {
			throw new GameGlobalException(Errors.LACK_CONTENT);
		}
		if (kbmContent.getCurrentUserId() == null) {
			throw new GameGlobalException(Errors.NOT_LOGIN);
		}
		if (kbmContent.getEndemicId() == null) {
			throw new GameGlobalException(Errors.NO_ENDEMIC);
		}
		idEntityAuto.setCreateId(kbmContent.getCurrentUserId());
		idEntityAuto.setModifiyId(kbmContent.getCurrentUserId());
		idEntityAuto.setEndemicId(kbmContent.getEndemicId());
		idEntityAuto.setSoftDelete(0);
	}

	@PreUpdate
	public void preUpdate(IdEntityAuto idEntityAuto) {
		Date now = new Date();
		idEntityAuto.setModifyTime(now);
		KbmContent kbmContent = idEntityAuto.getKbmContent();
		if (kbmContent == null) {
			throw new GameGlobalException(Errors.LACK_CONTENT);
		}
		idEntityAuto.setModifiyId(kbmContent.getCurrentUserId());

	}

	@PreRemove
	public void preRemove(IdEntityAuto idEntityAuto) {
		KbmContent kbmContent = idEntityAuto.getKbmContent();
		if (kbmContent == null) {
			throw new GameGlobalException(Errors.LACK_CONTENT);
		}
		if (!kbmContent.getDel().equals(1)) {
			throw new GameGlobalException(Errors.SYSTEM_ERROR);
		}

	}
}
